{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from retnet import RetNetDecoder\n",
    "from config import RetNetConfig\n",
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "config = RetNetConfig(decoder_layers=2, decoder_embed_dim=256, decoder_retention_heads=8, decoder_ffn_embed_dim=512, recurrent_chunk_size=2)\n",
    "embed_tokens = torch.nn.Embedding(100, config.decoder_embed_dim)\n",
    "model = RetNetDecoder(config, embed_tokens=embed_tokens)\n",
    "\n",
    "device = 'cpu'\n",
    "\n",
    "model = model.to(device)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "parallel vs recurrent True\n",
      "parallel vs chunkwise False\n"
     ]
    }
   ],
   "source": [
    "input_ids = torch.LongTensor([[1,2,1,2]]).to(device)\n",
    "\n",
    "model.chunkwise_recurrent = False\n",
    "parallel_state, _ = model(input_ids, features_only=True)\n",
    "\n",
    "\n",
    "incremental_state = {}\n",
    "rnn_state = []\n",
    "for i in range(input_ids.shape[1]):\n",
    "    rnn_h, _ = model(input_ids[:, :i+1], incremental_state=incremental_state, features_only=True)\n",
    "    rnn_state.append(rnn_h)\n",
    "rnn_state = torch.cat(rnn_state, dim=1)\n",
    "\n",
    "model.chunkwise_recurrent = True\n",
    "chunk_state, _ = model(input_ids, features_only=True)\n",
    "\n",
    "print('parallel vs recurrent', torch.allclose(parallel_state, rnn_state, atol=1e-5))\n",
    "print('parallel vs chunkwise', torch.allclose(parallel_state, chunk_state, atol=1e-5))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch-m1",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.3"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
